﻿@using Resources
@{
    Check.User(Can.AddItemsToForms);

    if (!UrlData[0].IsInt()) {
        Response.SetStatus(HttpStatusCode.BadRequest);
    }
    var formId = UrlData[0];
    var formFieldId = Request["formFieldId"];
    var edit = !formFieldId.IsEmpty();
    string commandText;
    dynamic formField = null;
    string displayOrder;


    var db = Database.Open((string) App.Database);
    
        commandText = @"SELECT FormName, MAX(DisplayOrder) AS DisplayOrder FROM Forms 
                        LEFT OUTER JOIN FormFields ON Forms.FormId = FormFields.FormId WHERE Forms.FormId = @0 GROUP BY FormName";
        var form = db.QuerySingle(commandText, formId);
        if (form == null) {
            Response.SetStatus(HttpStatusCode.BadRequest);
        }
    
    if(edit) {
        commandText = @"SELECT FieldName, LabelText, HelpText, DataTypeId, Required, MinLength, 
                        MaxLength, CompareTo, RequiredErrorMessage, MinLengthErrorMessage, MaxLengthErrorMessage, RangeErrorMessage, 
                        CompareToErrorMessage, DisplayOrder FROM FormFields WHERE FormFieldId = @0";
        formField = db.QuerySingle(commandText, formFieldId);
    }
    

    if (edit) {
        displayOrder = formField.DisplayOrder.ToString();
    }
    else {
        displayOrder = form.DisplayOrder == null ? "1" : (form.DisplayOrder + 1).ToString();
    }
    
    Validation.RequireFields("FieldName", "DataTypeId", "LabelText");
    Validation.Add("FieldName", Validator.Regex(@"[a-zA-Z\-\s]+", "Letters and dashes only, please"));
    Validation.Add("MinLength", Validator.Integer());
    Validation.Add("MaxLength", Validator.Integer());
    Validation.Add("RequiredErrorMessage", Validator.StringLength(150));
    Validation.Add("MinLengthErrorMessage", Validator.StringLength(150));
    Validation.Add("MaxLengthErrorMessage", Validator.StringLength(150));
    Validation.Add("RangeErrorMessage", Validator.StringLength(150));
    
    commandText = @"SELECT DataTypeId, DataType, Description FROM FieldDataTypes";
    var fieldTypes = db.Query(commandText).Select(f => new SelectListItem {
        Value = f.DataTypeId.ToString(),
        Text = f.DataType + " (" + f.Description + ")",
        Selected = formField != null ? formField.DataTypeId == f.DataTypeId: false
    });
    
    commandText = "SELECT FormFieldId, FieldName FROM FormFields WHERE FormId = @0";
    var compareTo = db.Query(commandText, formId).Select(c => new SelectListItem {
        Value = c.FormFieldId.ToString(),
        Text = c.FieldName,
        Selected = formField != null ? formField.CompareTo == c.FormFieldId : false
    });
    
    if (IsPost && Validation.IsValid()) {
        var fieldName = Request["FieldName"];
        var dataTypeId = Request["DataTypeId"];
        var labelText = Request["LabelText"];
        var helpText = Request["HelpText"].OrDbNull();
        var required = Request["Required"].IsOn();
        var requiredErrorMessage = Request["RequiredErrorMessage"].OrDbNull();
        var minLength = Request["MinLength"].OrDbNull();
        var minLengthErrorMessage = Request["MinLengthErrorMessage"].OrDbNull();
        var maxLength = Request["MaxLength"].OrDbNull();
        var maxLengthErrorMessage = Request["MaxLengthErrorMessage"].OrDbNull();
        var rangeErrorMessage = Request["RangeErrorMessage"].OrDbNull();
        var compareToField = Request["CompareTo"].OrDbNull();
        var compareToErrorMessage = Request["CompareToErrorMessage"].OrDbNull();
        displayOrder = Request["DisplayOrder"];
        if (edit) {
            commandText = @"UPDATE FormFields SET FieldName = @0, LabelText = @1, HelpText = @2, DataTypeId = @3, Required = @4, MinLength = @5, 
                        MaxLength = @6, CompareTo = @7, RequiredErrorMessage = @8, MinLengthErrorMessage = @9, MaxLengthErrorMessage = @10, 
                        RangeErrorMessage = @11, CompareToErrorMessage = @12, DisplayOrder = @13 WHERE FormFieldId = @14";
            db.Execute(commandText, fieldName, labelText, helpText, dataTypeId, required, minLength, maxLength, compareToField,
                       requiredErrorMessage, minLengthErrorMessage, maxLengthErrorMessage, rangeErrorMessage, compareToErrorMessage, displayOrder, formFieldId);
            Response.Redirect("~/Admin/Widgets/FormManager/" + formId);
        }
        commandText = @"INSERT INTO FormFields (FormId, FieldName, LabelText, HelpText, DataTypeId, Required, MinLength, 
                        MaxLength, CompareTo, RequiredErrorMessage, MinLengthErrorMessage, MaxLengthErrorMessage, RangeErrorMessage, 
                        CompareToErrorMessage, DisplayOrder) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14)";
        db.Execute(commandText, formId, fieldName, labelText, helpText, dataTypeId, required, minLength, maxLength, compareToField,
                   requiredErrorMessage, minLengthErrorMessage, maxLengthErrorMessage, rangeErrorMessage, compareToErrorMessage, displayOrder);
        Response.Redirect(Request.Url + "/1");
    }
    
}
<form method="post">
    <fieldset>
        <legend>@(Request["formFieldId"].IsEmpty() ? "Add" : "Edit") @(UrlData[1].AsInt() == 1 ? "Another " : "") Field @(Request["formFieldId"].IsEmpty() ? "To" : "In") @form.FormName</legend>
        @ControlGroup.TextBox("Field Name: ", "FieldName", formField != null ? formField.FieldName : null)
        @ControlGroup.RadioButtonGroup("Field Type: ", "DataTypeId", fieldTypes, formField != null ? formField.DataTypeId.ToString() : null)
        @ControlGroup.TextBox("Label Text: ", "LabelText", formField != null ? formField.LabelText : null, helperText: AdminResource.FormWidgetLabelTextHelpText)
        @ControlGroup.TextArea("Help Text: ", "HelpText", formField != null ? formField.HelpText : null, helperText: AdminResource.FormWidgetHelpTextHelpText)
        @ControlGroup.CheckBox("Required?", "Required",  formField != null ? formField.Required : false)
        @ControlGroup.TextBox("Error Message for Required: ", "RequiredErrorMessage", formField != null ? formField.RequiredErrorMessage : null, new {style = "width:100%"}, AdminResource.FormWidgetRequiredErrorMessageHelpText)
        @ControlGroup.TextBox("Minimum Length: ", "MinLength", formField != null ? formField.MinLength : null)
        @ControlGroup.TextBox("Error Message for Minimum Length: ", "MinLengthErrorMessage", formField != null ? formField.MinLengthErrorMessage : null, new {style = "width:100%"}, AdminResource.FormWidgetMinLengthErrorMessageHelpText)
        @ControlGroup.TextBox("Maximum Length: ", "MaxLength", formField != null ? formField.MaxLength : null)
        @ControlGroup.TextBox("Error Message for Maximum Length: ", "MaxLengthErrorMessage", formField != null ? formField.MaxLengthErrorMessage : null, new {style = "width:100%"}, AdminResource.FormWidgetMaxLengthErrorMessageHelpText)
        @ControlGroup.TextBox("Range Error Message: ", "RangeErrorMessage", formField != null ? formField.RangeErrorMessage : null, textBoxHtmlAttributes: new {style = "width:100%"}, helperText: AdminResource.FormWidgetRangeErrorMessageHelpText)
        @if (compareTo.Any()) {
            @ControlGroup.DropDownList("Compare To: ", "CompareTo", compareTo, " --Select Field-- ")
            @ControlGroup.TextBox("Error Message for Compare To: ", "CompareToErrorMessage", formField != null ? formField.CompareToErrorMessage : null, new {style = "width:100%"})
        }
        @ControlGroup.TextBox("Display Order: ", "DisplayOrder", displayOrder, new {style = "width:20px"})
        @ControlGroup.Button()
    </fieldset>
</form>
